package com.xin.data.simbapesa.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.IntentSenderRequest;
import androidx.activity.result.contract.ActivityResultContracts;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.xin.data.simbapesa.PathMaping;
import com.xin.data.simbapesa.R;
import com.xin.data.simbapesa.SimbaApp;
import com.xin.data.simbapesa.analysis.AnalysisUtil;
import com.xin.data.simbapesa.api.ConvertUrl;
import com.xin.data.simbapesa.api.PU;
import com.xin.data.simbapesa.api.RxHttp;
import com.xin.data.simbapesa.api.U;
import com.xin.data.simbapesa.base.BaseActivity;
import com.xin.data.simbapesa.base.BaseDialog;
import com.xin.data.simbapesa.base.BaseParams;
import com.xin.data.simbapesa.databinding.SimbaStartActivityBinding;
import com.xin.data.simbapesa.device.ImmediateUpdateManager;
import com.xin.data.simbapesa.dialog.UpdateDialog;
import com.xin.data.simbapesa.obj.SimbaAppInfo;
import com.xin.data.simbapesa.utils.AESCryptUtilJar;
import com.xin.data.simbapesa.utils.DateUtils;
import com.xin.data.simbapesa.utils.JsonParse;
import com.xin.data.simbapesa.utils.LogUtil;
import com.xin.data.simbapesa.utils.PhoneUtils;
import com.xin.data.simbapesa.utils.ResUtils;
import com.xin.data.simbapesa.utils.SpUtils;

import java.util.HashMap;
import java.util.TimeZone;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

public class SimbaStartActivity extends BaseActivity<SimbaStartActivityBinding> {


    ImmediateUpdateManager updateManager = null;

    UpdateDialog updateDialog;


    @Override
    protected SimbaStartActivityBinding initViewBinding(LayoutInflater inflater) {
        return SimbaStartActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {
        int radius = ResUtils.d(R.dimen.dp_12);
        Glide.with(binding.tvIcon.getContext()).load(R.mipmap.logo).placeholder(R.mipmap.logo).apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(radius, 0, RoundedCornersTransformation.CornerType.ALL))).into(binding.tvIcon);
        Glide.with(getActivity()).load(R.mipmap.sbg).placeholder(R.color.wbg).into(binding.tvImg);
        binding.getRoot().setPadding(0, 0, 0, 0);
    }

    @Override
    protected void initData() {
        UP_TYPE1 = PU.P1;
        UP_TYPE2 = PU.P2;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getTime();
    }



    void showDialog() {
        showTipsDialog("", "", ResUtils.s(R.string.start_btn_retry), ResUtils.s(R.string.start_net_failed), false, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {
                getTime();
            }

            @Override
            public void btnOnClickCancel() {
                System.exit(0);
            }

            @Override
            public void btnOnClickColse() {
                System.exit(0);
            }
        });
    }

    void getTime() {

        showLoading("");

        JsonObject json = BaseParams.getJsonObject(getActivity(), U.timePath);
        json.addProperty("tz", TimeZone.getDefault().getID());
        json.addProperty("p", U.URL_PRODUCT);

        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-getTime post->" + U.timeUrl);
        LogUtil.e("me", data + "<-getTime data->");
        RxHttp.post(U.timeUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String response) {
                        if (!TextUtils.isEmpty(response)) {
                            String rjson = AESCryptUtilJar.decryptDefault(response);
                            LogUtil.e("me", response + "<-getTime json->" + rjson);
                            if (JsonParse.getCode(rjson)) {
                                ConvertUrl.convertUrl(getActivity(), JsonParse.getTimeJson(rjson));
                                PU.queryDeviceInfoTypes(getActivity());
                                getAppInfo();
                                AnalysisUtil.INSTANCE.initAfterHadZone(getApplication());
                            } else {
                                showDialog();
                                hideLoading();
                            }
                        } else {
                            showDialog();
                            hideLoading();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e != null) {
                            LogUtil.e("me", "getTime e->" + e);
                        }
                        hideLoading();
                        showDialog();
                    }

                    @Override
                    public void onComplete() {
                    }
                });


    }


    void getAppInfo() {
        showLoading("");
        String path = PathMaping.PathList[0];
        JsonObject json = BaseParams.getJsonObject(getActivity(), path);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_MAIN_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", data + "--getAppInfo post--" + json);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(String response) {
                        hideLoading();
                        if (!TextUtils.isEmpty(response)) {
                            String rjson = AESCryptUtilJar.decryptDefault(response);
                            LogUtil.e("me", "getAppInfo json->" + rjson);
                            if (JsonParse.getCode(rjson)) {
                                userProcess(new UserProcessInterface() {
                                    @Override
                                    public void onRequestResult() {
                                        SpUtils.save_string(getActivity(), SpUtils.KEY_APP_INFO, rjson);
                                        SimbaAppInfo appInfo = JsonParse.appInfoJson2Obj(rjson);
                                        SimbaApp.getInstance().setAppInfo(appInfo);
//                                        toHome();

                                        if (PhoneUtils.isForceUpdate(getActivity())) {
                                            initUpdate();
                                            showUpdateDialog();
                                        } else {
                                            toHome();
                                        }

                                    }
                                }, true);
                            } else {
                                showDialog();
                            }
                        } else {
                            showDialog();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                        showDialog();
                        if (e != null) {
                            LogUtil.e("me", "getAppInfo e->" + e);
                        }
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    final ActivityResultLauncher<IntentSenderRequest> updateLauncher =
            registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(),
                    result -> {
                        try {
                            if (result.getResultCode() == RESULT_OK) {
                                toHome();
                                SpUtils.save_boolean(SimbaApp.getInstance(), SpUtils.KEY_UPDATE + "_" + U.URL_PHONE + "_" + DateUtils.getYear() + "_" + DateUtils.getMonth() + "_" + DateUtils.getDay(), true);
                            } else {
                                toHome();
                            }
                        } catch (Exception e) {
                            LogUtil.e("me", "updateLauncher e->" + e);
                            toHome();
                        }
                    });

    void initUpdate() {
        try {
            updateManager = new ImmediateUpdateManager(this, true, updateLauncher, null);
        } catch (Exception e) {
            toHome();
        }
    }

    void showUpdateDialog() {
        if (!isFinishing() && binding != null && SimbaApp.getInstance().getAppInfo() != null && SimbaApp.getInstance().getAppInfo().getUpdateInfo() != null) {
            if (updateDialog != null) {
                updateDialog.dismiss();
                updateDialog=null;
            }
            updateDialog = new UpdateDialog(getActivity());
            updateDialog.setOnBtnClickListener(new UpdateDialog.BtnClickListener() {
                @Override
                public void btnOnClickOk() {
                    PU.userBuriedPoint(PU.P301, "");
                    if (updateManager != null) {
                        updateManager.checkAndStartUpdateAsync(new Function0<Unit>() {
                            @Override
                            public Unit invoke() {
                                return null;
                            }
                        }, null);
                    }
                }

                @Override
                public void btnOnClickCancel() {
                    PU.userBuriedPoint(PU.P302, "");
                }

                @Override
                public void btnOnClickColse() {
                    PU.userBuriedPoint(PU.P302, "");
                }
            });
            updateDialog.setData(SimbaApp.getInstance().getAppInfo().getUpdateInfo());
            updateDialog.show();
            PU.userBuriedPoint(PU.P300, "");
        }
    }


    void toHome() {
        U.URL_USERID = SpUtils.get_string(this, SpUtils.KEY_USERID, "");
        U.URL_TOKEN = SpUtils.get_string(this, SpUtils.KEY_TOKEN, "");
        U.URL_PHONE = SpUtils.get_string(this, SpUtils.KEY_PHONE, "");

        if (!TextUtils.isEmpty(U.URL_TOKEN)) {
            AnalysisUtil.INSTANCE.initAfterLogin(getApplication());
            startActivity(new Intent(this, SimbaHomeActivity.class));
        } else {
            startActivity(new Intent(this, SimbaLoginActivity.class));
        }
        finish();
    }



}
